/*
    Find PID By Process name
    For More Codes: https://github.com/Whitecat18/Rust-for-Malware-Development.git
    Resources Used: MSDOS
    @5mukx
*/

macro_rules! okey {
    ($msg:expr, $($arg:expr), *) => {
        println!("[+] {}", format!($msg, $($arg),*));
    }
}
macro_rules! error {
    ($msg:expr, $($arg:expr), *) => {
        println!("[!] {}", format!($msg,$($arg),*));
    };
}


use std::{ffi::CString, mem};

use winapi::um::{
    errhandlingapi::GetLastError, 
    handleapi::CloseHandle, 
    tlhelp32::{CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS
}};

fn get_pid(process_name: &str) -> u32{
    unsafe{
        let mut pe: PROCESSENTRY32 = std::mem::zeroed();
        pe.dwSize = mem::size_of::<PROCESSENTRY32>() as u32;

        let snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if snap.is_null(){
            error!("Error while snapshoting processes : Error : {}",GetLastError());
            std::process::exit(0);
        }

        let mut pid = 0;

        let mut result = Process32First(snap, &mut pe) != 0;

        while result{

            let exe_file = CString::from_vec_unchecked(pe.szExeFile
                .iter()
                .map(|&file| file as u8)
                .take_while(|&c| c!=0)
                .collect::<Vec<u8>>(),
            );

            if exe_file.to_str().unwrap() == process_name {
                pid = pe.th32ProcessID;
                break;
            }
            result = Process32Next(snap, &mut pe) !=0;
        }

        if pid == 0{
            error!("Unable to get PID for {}: {}",process_name , "PROCESS DOESNT EXISTS");           
            std::process::exit(0);
        }
    
        CloseHandle(snap);
        pid
    }
}

fn main(){
    // talking snapshot of all in the system.
    
    let process_name = "notepad.exe";
    let pid = get_pid(&process_name);
    okey!("Got PID: {}",pid);

}
